#!/usr/bin/env python
# -*- coding: utf-8 -*-

from django.db import models
from django.core.files.storage import FileSystemStorage
import settings
import re
import os
from documents.models import Item

def download_file_name(instance, filename):
    document = instance.item.document
    module_term = document.module_term
    module_part = document.module_part
    module = module_term.module
    
    new_filename_ascii = module.get_short()[:5] + '_' + \
                         module_term.semester.get_short() + '_' + \
                         module_part.get_short() + '_' + \
                         document.name + '_' + \
                         instance.item.user.username
    
    new_filename = unicode(new_filename_ascii)
                   
    new_filename = new_filename.replace(u'Ü', u'U').replace(u'ü', u'u').replace(u'Ö', u'O').replace(u'ö', u'o').replace(u'Ä', u'A').replace(u'ä', u'a').replace(u'ß', u'ss').replace(u' ', u'_')
                   
    new_filename = re.sub(u'[^A-Za-z0-9_]+', '', new_filename)
    
    new_filename = new_filename.lower()
    
    extension = guess_extension(instance.upload.name)
    
    new_filename = new_filename[len(new_filename)+len(extension)-250:] + extension
    
    return new_filename

def guess_extension(filename):
    """
    Guess the extension of given filename.
    """
    root,ext = os.path.splitext(filename)
    if any([filename.endswith(x) for x in settings.DOUBLE_EXTENSIONS]):
        root, first_ext = os.path.splitext(root)
        ext = first_ext + ext
    return ext

fs = FileSystemStorage(location = settings.DOWNLOAD_ROOT)
class Upload(models.Model):
    """        
    Model for an Upload - belonging to a certain Item
    """
    
    upload = models.FileField(upload_to = download_file_name, storage = fs)
    
    item = models.OneToOneField(Item)
    
    @staticmethod
    def delete_handler(instance, **kwargs):
        """
        Additionaly removes the file from disk
        """
        if isinstance(instance, Upload):
            try:
                # on_delete: delete file - don't save afterwards
                instance.upload.delete(False)
            except OSError:
                # happens in case for some reason anybody has
                # already deleted the corresponding file
                pass
        
    def save(self, *args, **kwargs):
        """
        Make sure dead files are deleted
        """
        try:
            old_upload = Upload.objects.get(id = self.id).upload
            
            if old_upload != self.upload:
                old_upload.delete(save=False)
        except Upload.DoesNotExist:
            pass
        finally:
            # delete from db
            super(Upload, self).save(*args, **kwargs)
        
    
    def __unicode__(self):
        return self.item.document.name + " " + self.item.user.username
    
# register pre_delete connector in order for the Upload to detect a
# cascaded/non-cascaded delete because overriding delete() is not enough
models.signals.pre_delete.connect(Upload.delete_handler)

